<template>
  <div>
    <el-card class="box-card">
      <Table max-height="300" :columns="columns" :data="record" stripe border>
        <template slot-scope="{ row }" slot="inOut">
          <el-tag type="success" v-if="row.inOut === '收入'">收入</el-tag>
          <el-tag type="warning" v-else>支出</el-tag>
        </template>

        <template slot-scope="{ row }" slot="action">
          <Button type="primary" size="small" style="margin-right: 5px" @click="revamp(row)">修改</Button>
          <Button type="error" size="small" @click="del(row)">删除</Button>
        </template>
      </Table>
      <div id="inMain" style="width: 350px;height:150px;"></div>
      <div id="outMain" style="width: 350px;height:150px;"></div>
    </el-card>

    <Drawer title="修改" v-model="show" width="720" :mask-closable="false" :styles="styles">
      <el-form ref="submitFormRef" :model="submitForm" label-width="80px">
        <el-form-item label="金额">
          <el-input type="number" v-model="submitForm.expend"></el-input>
        </el-form-item>
        <el-form-item label="账户">
          <el-select v-model="submitForm.account">
            <el-option label="我的钱包" value="我的钱包"></el-option>
            <el-option label="银行卡" value="银行卡"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用途">
          <el-cascader
            :options="options"
            :show-all-levels="false"
            v-model="submitForm.purpose"
            placeholder="不修改即为原值"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="日期">
          <el-col :span="11">
            <el-date-picker type="date" v-model="submitForm.date" style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="submitForm.remark" placeholder="请填写备注，可以为空"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">修改</el-button>
          <el-button @click="show = false">取消</el-button>
        </el-form-item>
      </el-form>
    </Drawer>
  </div>
</template>

<script>
import echarts from "echarts";
export default {
  data() {
    return {
      dialogVisible: false,
      columns: [
        {
          type: "index",
          width: 50,
          align: "center"
        },
        {
          title: "日期",
          key: "date",
          width: 110,
          sortable: true
        },
        {
          title: "收支",
          key: "inOut",
          slot: "inOut",
          width: 80
        },
        {
          title: "金额",
          key: "reExpend",
          width: 90,
          sortable: true
        },
        {
          title: "账户",
          key: "account",
          width: 120,
          sortable: true
        },
        {
          title: "用途",
          key: "rePurpose",
          width: 120,
          sortable: true
        },
        {
          title: "备注",
          key: "remark"
        },
        {
          title: "操作",
          slot: "action",
          width: 150,
          align: "center"
        }
      ],
      submitForm: {
        id: "",
        telephone: "",
        expend: 0,
        account: "",
        date: "",
        purpose: "",
        remark: ""
      },
      outOptions: "",
      inOptions: "",
      options: [],
      record: [],
      // 控制抽屉的显示与否
      show: false,
      // 抽屉的显示样式
      styles: {
        height: "calc(100% - 55px)",
        overflow: "auto",
        paddingBottom: "53px",
        position: "static"
      }
    };
  },
  mounted() {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById("inMain"));
    var meChart = echarts.init(document.getElementById("outMain"));
    let outData = [];
    let inData = [];
    this.record.forEach(item => {
      if (item.inOut === "收入") {
        inData.push(item.purpose);
      } else {
        outData.push(item.purpose);
      }
    });

    inData = Array.from(new Set(inData));
    outData = Array.from(new Set(outData));
    let inCome = [];
    let outPut = [];
    inData.forEach(item => {
      let va = {
        name: item.trim(),
        value: 0
      };
      this.record.forEach(it => {
        if (it.purpose.trim() === item.trim()) {
          va.value += it.expend;
        }
      });
      inCome.push(va);
    });

    outData.forEach(item => {
      let va = {
        name: item.trim(),
        value: 0
      };
      this.record.forEach(it => {
        if (it.purpose.trim() === item.trim()) {
          va.value += it.expend;
        }
      });
      va.value = 0 - va.value;
      va.name= va.name.substring(5, 10);
      outPut.push(va);
    });

    // 指定图表的配置项和数据
    var inOption = {
      series: [
        {
          name: "访问来源",
          type: "pie",
          radius: "55%",
          roseType: 'angle',
          data: inCome
        }
      ]
    };
    var outOption = {
      series: [
        {
          name: "访问来源",
          type: "pie",
          radius: "55%",
          roseType: 'angle',
          data: outPut
        }
      ]
    };
    
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(inOption);
    meChart.setOption(outOption);
  },
  created() {
    this.outOptions = this.$store.state.outOptions;
    this.inOptions = this.$store.state.inOptions;
    this.record = this.$store.state.record;
    this.record.forEach(item => {
      if (item.expend < 0) {
        item.inOut = "支出";
        item.reExpend = 0 - item.expend;
        item.rePurpose = item.purpose.substr(-5);
      } else {
        item.inOut = "收入";
        item.reExpend = item.expend;
        item.rePurpose = item.purpose;
      }
    });
  },
  methods: {
    // 格式化日期
    dateForm(date) {
      let d = new Date(date);
      d.setDate(d.getDate() + 0);
      let m = d.getMonth() + 1;
      return d.getFullYear() + "-" + m + "-" + d.getDate();
    },
    revamp(row) {
      this.show = true;
      this.submitForm.telephone = window.sessionStorage.getItem("telephone");
      this.submitForm.id = row.id;
      this.submitForm.expend = row.reExpend;
      this.submitForm.date = row.date;
      this.submitForm.remark = row.remark;
      this.submitForm.account = row.account;
      this.submitForm.inOut = row.inOut;
      if (row.inOut === "收入") {
        this.options = this.inOptions;
        this.submitForm.purpose = row.purpose;
      } else {
        this.options = this.outOptions;
        this.submitForm.purpose = row.purpose.split(",");
      }
    },
    async onSubmit() {
      if (this.submitForm.expend <= 0) {
        this.$message({
          showClose: true,
          message: "金额不能小于0",
          type: "warning"
        });
        return;
      }
      if (this.submitForm.inOut === "支出") {
        this.submitForm.expend = 0 - this.submitForm.expend;
      }
      const { data: result } = await this.$http.put("revamp", this.submitForm);
      if (result.errorCode != 0) {
        this.$message({
          showClose: true,
          message: "修改失败！",
          type: "warning"
        });
        return;
      }
      this.$message({
        showClose: true,
        message: "修改成功！",
        type: "success"
      });

      const res = await this.$http.get("record", {
        params: { telephone: window.sessionStorage.getItem("telephone") }
      });
      // 遍历获取到的数据，按时间日期渲染
      res.data.data.result.recordset.forEach(item => {
        item.date = this.dateForm(item.date);
      });
      this.record = res.data.data.result.recordset;
      this.$store.commit("setRecord", this.record);
      this.record.forEach(item => {
        if (item.expend < 0) {
          item.inOut = "支出";
          item.reExpend = 0 - item.expend;
          item.rePurpose = item.purpose.substr(-5);
        } else {
          item.inOut = "收入";
          item.reExpend = item.expend;
          item.rePurpose = item.purpose;
        }
      });
      this.show = false;
    },
    async del(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: result } = await this.$http.delete("delete/" + row.id);
          if (result.errorCode != 0) {
            this.$message({
              showClose: true,
              message: "删除失败！",
              type: "warning"
            });
            return;
          }
          const res = await this.$http.get("record", {
            params: { telephone: window.sessionStorage.getItem("telephone") }
          });
          // 遍历获取到的数据，按时间日期渲染
          res.data.data.result.recordset.forEach(item => {
            item.date = this.dateForm(item.date);
          });
          this.record = res.data.data.result.recordset;
          this.$store.commit("setRecord", this.record);
          this.record.forEach(item => {
            if (item.expend < 0) {
              item.inOut = "支出";
              item.reExpend = 0 - item.expend;
              item.rePurpose = item.purpose.substr(-5);
            } else {
              item.inOut = "收入";
              item.reExpend = item.expend;
              item.rePurpose = item.purpose;
            }
          });

          this.$message({
            showClose: true,
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            showClose: true,
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>

<style lang="less" scoped>
.box-card {
  height: 100%;
  width: 80%;
  margin: 20px auto;
}
#inMain {
  float: left;
}
#outMain {
  float: right;
}
</style>